using System;
using System.ServiceModel;
using Microsoft.Practices.ServiceLocation;

namespace Sogeti.Guidelines.WCF.Hosting
{
    public class CommonServiceHost<TContainerProvider> : ServiceHost
        where TContainerProvider : IContainerProvider
    {
        public IServiceLocator Container { set; get; }

        protected CommonServiceHost()
        {
        }

        public CommonServiceHost(Type serviceType, params Uri[] baseAddresses)
            : base(serviceType, baseAddresses)
        {
            var containerProvider = typeof (TContainerProvider).New<TContainerProvider>();
            containerProvider.EnsureConfiguration();
            Container = containerProvider.CreateContainer();
        }

        protected override void OnOpening()
        {
            if (Container == null)
                throw new ApplicationException("The ServiceHost's Container property can't be null");

            new CommonServiceHostServiceBehavior(Container).AddToHost(this);
            base.OnOpening();
        }
    }
}